
package neteasefilters.filters;

import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RadialGradient;

public class CvRadialDOF implements IImageFilter {

    // 径向虚化

    int posX, posY;
    double size;

    // 参数说明：posX,posY,是虚化中心点的位置（坐标）。size是虚化的范围大小（比例，0-1之间）。
    // 虚化的程度未做参数

    public CvRadialDOF(int _x, int _y, double _size) {
        posX = _x;
        posY = _y;
        size = _size;
    }

    private Image Get_Radial_Mask(int w, int h, float centerX, float centerY, double size) {
        centerX = centerX * w;
        centerY = centerY * h;
        size = (w > h ? h : w) * size;

        int[] _color = new int[3];
        _color[0] = Color.WHITE;
        _color[1] = Color.WHITE;
        _color[2] = Color.BLACK;

        float[] _pos = new float[3];
        _pos[0] = 0;
        _pos[1] = 0.5f;
        _pos[2] = 1.0f;

        RadialGradient grad = new RadialGradient(centerX, centerY, (float)size, _color, _pos,
                android.graphics.Shader.TileMode.CLAMP);
        Paint p = new Paint();
        p.setDither(true);
        p.setShader(grad);

        Bitmap bitmap = Bitmap.createBitmap(w, h, Config.ARGB_8888);
        Canvas c = new Canvas(bitmap);
        c.drawRect(0, 0, w, h, p);

        Image _out = new Image(bitmap);
        _out.updateColorArray();

        return _out;
    }

    @Override
    public Image process(Image imageIn) {
        int w = imageIn.getWidth();
        int h = imageIn.getHeight();

        if (posX < 0 || posY < 0 || posX > w || posY > h)
            return imageIn;

        if (size < 0 || size > 1.0)
            return imageIn;

        float cx = (float)posX / w;
        float cy = (float)posY / h;

        Image _mask;
        _mask = Get_Radial_Mask(w, h, cx, cy, size);

        imageIn.updateColorArray();
        int[] _inpix = imageIn.getColorArray();
        int[] _maskpix = _mask.getColorArray();

        LibCvFilter.AddByMask(_inpix, _maskpix, w, h);
        imageIn.setColorArray(_inpix);
        System.gc();

        return imageIn;
    }
}
